package com.bifang.core.quartz.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.common.exception.AppException;
import com.bifang.common.vo.QrtzTriggersLogVO;
import com.bifang.core.dao.model.QrtzTriggers;
import com.bifang.core.dao.model.QrtzTriggersLog;
import com.bifang.core.dao.service.QrtzTriggersLogService;
import com.bifang.core.dao.service.QrtzTriggersService;
import com.bifang.core.quartz.integration.QuartzLogIntegration;
import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class QuartzLogIntegrationImpl implements QuartzLogIntegration {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired QrtzTriggersService qrtzTriggersService;
    @Autowired QrtzTriggersLogService qrtzTriggersLogService;

    @Value("${spring.quartz.properties.org.quartz.scheduler.instanceName}")
    private String schedName;

    @Override
    public QrtzTriggersLogVO insertLog(JobExecutionContext context) {
        QrtzTriggersLogVO qrtzTriggersLogVO = new QrtzTriggersLogVO();
        qrtzTriggersLogVO.setTriggerName(context.getTrigger().getKey().getName());
        qrtzTriggersLogVO.setTriggerGroup(context.getTrigger().getKey().getGroup());
        qrtzTriggersLogVO.setExFlag(0);
        try {
            qrtzTriggersLogVO.setSchedName(context.getScheduler().getSchedulerName());
        } catch (SchedulerException e) {
            logger.error("获取任务SchedName失败", e);
        }
        String schedNameLocal = qrtzTriggersLogVO.getSchedName();
        if (StringUtils.isBlank(qrtzTriggersLogVO.getSchedName())) {
            schedNameLocal = schedName;
        }
        if (StringUtils.isBlank(schedNameLocal)
                || StringUtils.isBlank(qrtzTriggersLogVO.getTriggerGroup())
                || StringUtils.isBlank(qrtzTriggersLogVO.getTriggerName())) {
            throw new AppException("保存日志定时任务Trigger相关参数有为空");
        }
        QueryWrapper<QrtzTriggers> qrtzTriggersQueryWrapper = new QueryWrapper<>();
        qrtzTriggersQueryWrapper
                .lambda()
                .eq(QrtzTriggers::getSchedName, schedNameLocal)
                .eq(QrtzTriggers::getTriggerName, qrtzTriggersLogVO.getTriggerName())
                .eq(QrtzTriggers::getTriggerGroup, qrtzTriggersLogVO.getTriggerGroup());
        QrtzTriggers qrtzTriggers = qrtzTriggersService.getOne(qrtzTriggersQueryWrapper);
        QrtzTriggersLog qrtzTriggersLog = Convert.convert(QrtzTriggersLog.class, qrtzTriggers);
        qrtzTriggersLog.setTriggersLogId(qrtzTriggersLogVO.getTriggersLogId());
        qrtzTriggersLog.setStartTime(new Date());
        Integer ym =
                Integer.parseInt(
                        DateUtil.format(DateUtil.date(), DatePattern.PURE_DATE_PATTERN)
                                .substring(0, 6));
        qrtzTriggersLog.setYm(ym);
        qrtzTriggersLogService.save(qrtzTriggersLog);
        qrtzTriggersLogVO.setTriggersLogId(qrtzTriggersLog.getTriggersLogId());
        return qrtzTriggersLogVO;
    }

    @Override
    public void updateLog(QrtzTriggersLogVO qrtzTriggersLogVO) {
        if (qrtzTriggersLogVO.getTriggersLogId() == null) {
            throw new AppException("定时任务日志id不能为空");
        }
        String msg = qrtzTriggersLogVO.getMsg();
        if (StringUtils.isNotBlank(msg) && msg.length() > 500) {
            msg = msg.substring(0, 400);
        }
        UpdateWrapper<QrtzTriggersLog> qrtzTriggersLog = new UpdateWrapper();
        qrtzTriggersLog
                .lambda()
                .eq(QrtzTriggersLog::getTriggersLogId, qrtzTriggersLogVO.getTriggersLogId())
                .set(QrtzTriggersLog::getEndTime, new Date())
                .set(QrtzTriggersLog::getExFlag, qrtzTriggersLogVO.getExFlag())
                .set(QrtzTriggersLog::getMsg, msg);
        qrtzTriggersLogService.update(qrtzTriggersLog);
    }
}
